﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Globalization;
using Global.Helpers;
using System.Threading;
using System.Web;

namespace Infrastructure.Web.Mvc.Extensions
{
    public class BaseActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var lang = filterContext.RouteData.Values["lang"];
            if (lang != null &&
                !string.IsNullOrWhiteSpace(lang.ToString()) &&
               GamaOptions.Languages.ContainsKey(lang.ToString().ToLower()))
            {
                // set the culture from the route data (url)                   
                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang.ToString());
            }
            else
            {
                // load the culture info from the cookie
                var cookie = filterContext.HttpContext.Request.Cookies[GamaOptions.LanguageKey];
                var langHeader = string.Empty;
                if (cookie != null)
                {
                    // set the culture by the cookie content
                    langHeader = cookie.Value;
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(GamaOptions.Languages.ContainsKey(langHeader.ToString().ToLower()) ? langHeader : GamaOptions.LanguageDefault);
                }
                else
                {
                    // set the culture by the location if not speicified
                    langHeader = filterContext.HttpContext.Request.UserLanguages[0];
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(GamaOptions.Languages.ContainsKey(langHeader.ToString().ToLower()) ? langHeader : GamaOptions.LanguageDefault);
                }
                // set the lang value into route data
                filterContext.RouteData.Values["lang"] = GamaOptions.Languages.ContainsKey(langHeader.ToString().ToLower()) ? langHeader : GamaOptions.LanguageDefault;
            }

            // save the location into cookie
            HttpCookie _cookie = new HttpCookie(GamaOptions.LanguageKey, Thread.CurrentThread.CurrentUICulture.Name);
            _cookie.Expires = DateTime.Now.AddDays(GamaOptions.CookieTimeoutInDays);
            filterContext.HttpContext.Response.SetCookie(_cookie);

            //filterContext.HttpContext.Session.Add(GamaOptions.LanguageKey, Thread.CurrentThread.CurrentUICulture.Name);
            base.OnActionExecuting(filterContext);
        }
    }
}
